import React, { useState, useMemo } from "react";
// todo useMemo也是用来缓存函数的
// todo 用法和useCallback完全相同

// todo 完全可以当作vue的计算属性去理解

//! useCallback和useMemo的区别
// todo useCallback是真正的缓存函数
// todo useMemo缓存的是函数的返回值

//! useCallback和useMemo能否相互转换
// todo 只有useCallback可以写成useMemo，将之前的函数当作返回值，柯里化函数

const App = () => {
  const [count, setCount] = useState(1);
  const [num, setNum] = useState(1);

  const [arr] = useState([1, 2, 3, 4, 5, 6, 7]);

  const oddArr = useMemo(() => {
    return arr.filter((item) => item % 2);
  }, [arr]);

  const fn = () => {
    setCount((v) => v + 1);
  };
  const fn3 = () => {
    setNum((v) => v + 1);
  };

  const fn2 = useMemo(() => {
    console.log("fn2执行了");
    let sum = 0;
    for (let i = 0; i <= count * 1000; i++) {
      sum += i;
    }
    return sum;
  }, [count]);

  return (
    <>
      <h2>useMemo</h2>
      <p>{count}</p>
      <button onClick={fn}>btn</button>
      <p>{fn2}</p>

      <p>num: {num}</p>
      <button onClick={fn3}>btn</button>

      <ul>
        {oddArr.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </>
  );
};

export default App;
